import React from 'react';
import { message } from 'antd';
import { DownloadOutlined } from '@ant-design/icons';
import { Button } from 'antd';
import { v4 as uuidv4 } from 'uuid';


interface DownloadComponentProps {
  imageUrl: string | null;
}

const DownloadComponent: React.FC<DownloadComponentProps> = ({ imageUrl }) => {
  const handleDownload = async () => {
    console.log('下载imageUrl: ', imageUrl);
    if (!imageUrl) {
      message.error('没有可下载的图片');
      return;
    }

    try {
      const uniqueFileName = `${uuidv4()}.jpg`;
      console.log('fileName:', uniqueFileName);

      // 先尝试 fetch 下载
      try {
        const response = await fetch(imageUrl);
        if (response.ok) {
          // console.log('使用 fetch 下载');
          const blob = await response.blob();
          const blobUrl = window.URL.createObjectURL(blob);
          const link = document.createElement('a');
          link.href = blobUrl;
          link.download = uniqueFileName;
          link.setAttribute('target', '_blank');
          document.body.appendChild(link);
          link.click();
          document.body.removeChild(link);
          window.URL.revokeObjectURL(blobUrl);
        }
      } catch (fetchError) {
        // fetch 失败时使用 a 标签直接下载
        // console.log('使用 a标签 下载');
        const link = document.createElement('a');
        link.href = imageUrl;
        link.download = uniqueFileName;
        link.setAttribute('target', '_blank');
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
      }
    } catch (error) {
      console.error('下载失败:', error);
      message.error('下载失败，请稍后重试');
    }
  };

  return (
    <div>
      <Button
        icon={<DownloadOutlined />}
        onClick={handleDownload}
        type="text"
        disabled={!imageUrl}
        style={{ fontWeight: 'bold' }}
      >
        下载
      </Button>
    </div>
  );
};

export default DownloadComponent;